package com.mall.service.impl;

import com.mall.dao.ProductMapper;
import com.mall.enums.ProductStatusEnum;
import com.mall.enums.ResponseEnum;
import com.mall.pojo.Product;
import com.mall.service.ICategoryService;
import com.mall.service.IProductService;
import com.mall.vo.ProductDetailVo;
import com.mall.vo.ProductVo;
import com.mall.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: 黄建
 * @Date: 2020/1/25 15:06
 */
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<ProductVo> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        System.out.println("111");
        Set<Integer> categoryIdSet = new HashSet<>();
        if (categoryId != null) {
            categoryService.findSubCategoryId(categoryId, categoryIdSet);
            categoryIdSet.add(categoryId);
        }
        List<ProductVo> productVos = productMapper.selectByCategoryIdSet(categoryIdSet).stream().map(this::product2ProductVo).collect(Collectors.toList());

        return productVos;
    }

    @Override
    public ResponseVo<ProductDetailVo> getProductDetail(Integer productId) {
        Product result = productMapper.selectByProductId(productId);
        if (result.getStatus().equals(ProductStatusEnum.DELETE.getCode()) || result.getStatus().equals(ProductStatusEnum.OFF_SALE.getCode())) {
            return ResponseVo.error(ResponseEnum.PRODUCT_OFF_SALE_OR_DELETE);
        }
        ProductDetailVo productDetailVo = new ProductDetailVo();
        BeanUtils.copyProperties(result, productDetailVo);
        String[] subImage = result.getSubImages().split(",");
        productDetailVo.setSubImages(subImage);
        productDetailVo.setStock(result.getStock() > 100 ? 100 : result.getStock());

        return ResponseVo.success(productDetailVo);
    }

    private ProductVo product2ProductVo(Product product) {
        ProductVo productVo = new ProductVo();
        BeanUtils.copyProperties(product, productVo);
        return productVo;
    }
}
